package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.service.IYddCateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/ydd_cate")
@Slf4j
public class YddCateController {
    @Autowired
    private IYddCateService iYddCateService;

    /*
    * 数据回显, 当点击修改分类时,发送此请求
    * */
    @GetMapping("/rowInfo")
    public R rowInfo(Long id){
        log.info("信息为: {}",id);
        YddCate cate = iYddCateService.getById(id);
        R r=R.success("catename",cate);
        r.putData("id",id);
        r.putData("icon",cate.getIcon());
        r.putData("sort_num",cate.getSortNum());
        return r;
    }
    /*
    * 分页查询
    * */

    @GetMapping("/list")
    public R list(String catename,int page,int limit){
        Page<YddCate> yddCatePage = new Page<>(page,limit);
        LambdaQueryWrapper<YddCate> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(catename),YddCate::getCatename,catename);
        queryWrapper.orderByDesc(YddCate::getIcon);
        iYddCateService.page(yddCatePage, queryWrapper);
        R r=R.success("count",yddCatePage.getTotal());
        r.putData("pageSize",yddCatePage.getSize());
        r.putData("currentPage",yddCatePage.getCurrent());
        r.putData("data",yddCatePage.getRecords());
        return r;
    }
    @GetMapping("/del")
    public R  del(Long id){
        log.info("-----------------{}",id);
        boolean b = iYddCateService.removeById(id);
        R r=new R();
        if (b){
            r.setErrno(0);
        }else {
            r.setErrno(1000);
            r.setErrmsg("系统默认数据,不允许删除");
        }
        return r;
    }
    /*
    * 修改
    * */
    @PostMapping("/update")
    public R update(@RequestBody YddCate yddCate){
        iYddCateService.updateById(yddCate);
        R r=new R();
        r.setErrno(0);
        return r;

    }
    /*
    * 添加
    * */
    @PostMapping("/add")
    public R add(@RequestBody YddCate yddCate){
        log.info("数据为 {}",yddCate);
        yddCate.setDefaultData("1");
        iYddCateService.save(yddCate);
        R r=new R();
        r.setErrno(0);
        return r;
    }

    /*
    *
    * */
    @GetMapping("/all")
    public ResultData all(){
        LambdaQueryWrapper<YddCate> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(YddCate::getSortNum);
        List<YddCate> list = iYddCateService.list();
        return ResultData.ok("",list);
    }
}
